<?php

declare(strict_types=1);

namespace App\Common\Service;


use Hyperf\Guzzle\ClientFactory;
use League\Flysystem\Filesystem;

class Generator
{
    const NAME_URL = "https://www.qmsjmfb.com/erciyuan.php";
    const AVATAR_URL = "https://api.uomg.com/api/rand.avatar";
    const AVATAR_URL_BING = "https://cn.bing.com/images/async";
    const AVATAR_URL_SOGOU = "https://pic.sogou.com/api/pic/searchList";
    /**
     * http Client
     * @var
     */
    protected $httpClient;

    /**
     * user Agent
     * @var
     */
    protected $userAgent;

    /**
     * Filesystem
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * Generator constructor.
     * @param ClientFactory $clientFactory
     * @param Filesystem $filesystem
     */
    public function __construct(ClientFactory $clientFactory, Filesystem $filesystem)
    {
        $this->filesystem = $filesystem;
        $this->httpClient = $clientFactory->create(['timeout' => 30.0]);
        $this->userAgent = [
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'
        ];
    }

    /**
     * 昵称随机200
     * @return mixed
     */
    public function name100()
    {
        $options = [
            'headers' => $this->userAgent,
            'form_params' => [
                'sex' => 'all',
                'style' => 'all',
                'num' => 100
            ]
        ];
        $httpResponse = $this->httpClient->post(self::NAME_URL, $options);
        $resContents = $httpResponse->getBody()->getContents();
        preg_match("/<ul class=\"name_show\">(.*?)<div style=\"clear:both\"><\/div><\/ul>/ism", $resContents, $res);
        preg_match_all("/<li>(.*?)<\/li>/ism", $res[1], $nameArr);
        return $nameArr[1];
    }

    public function nicknameDict(){
        $namePath = BASE_PATH . '/storage/name.group';
        return explode(',', file_get_contents($namePath));
    }


    /**
     * 单个随机头像
     * @return mixed
     */
    public function avatar()
    {
        $options = [
            'headers' => $this->userAgent,
            'query' => [
                'format' => 'json'
            ]
        ];
        $httpResponse = $this->httpClient->get(self::AVATAR_URL, $options);
        $resContents = $httpResponse->getBody()->getContents();
        return json_decode($resContents, true)['imgurl'];
    }

    /**
     * 必应头像
     * @return array
     */
    public function avatarBing()
    {
        $imgArr = [];
        $options = [
            'headers' => $this->userAgent,
            'query' => [
                'q' => '头像',
                'first' => 0,
                'count' => 100,
                'relp' => 100,
                'scenario' => 'ImageBasicHover'
            ]
        ];
        $httpResponse = $this->httpClient->get(self::AVATAR_URL_BING, $options);
        $resContents = $httpResponse->getBody()->getContents();
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $internalErrors = libxml_use_internal_errors(true);
        $dom->loadHTML($resContents);
        libxml_use_internal_errors($internalErrors);
        $dom->normalizeDocument();
        $xpath = new \DOMXPath($dom);
        $imgs = $xpath->query('//*[@class=\'mimg\']');
        foreach ($imgs as $img) {
            array_push($imgArr, $img->getAttribute('src'));
        }
        return $imgArr;
    }


    /**
     * 搜狗pic 100
     * @return array
     */
    public function avatarSoGou100()
    {
        $options = [
            'headers' => $this->userAgent,
            'query' => [
                'tagQSign' => '',
                'forbidqc' => '',
                'entityid' => '',
                'query' => '头像',
                'mode' => 1,
                'st' => '',
                'start' => 0,
                'xml_len' => 100,
                '_' => (int)(microtime(true) * 1000)
            ]
        ];
        $httpResponse = $this->httpClient->get(self::AVATAR_URL_SOGOU, $options);
        $resContents = $httpResponse->getBody()->getContents();
        return array_column(json_decode($resContents, true)['items'], 'picUrl');
    }

    /**
     * 阿里OSS 470+ 头像
     * @param int|null $num
     * @return array
     */
    public function randAvatarOss(?int $num = null){
        $res = $this->filesystem->listContents(env('OSS_AVATAR_DIR','face'), false);
        $res = array_column($res, 'path');
        if ($num){
            $ress = [];
            $keys = array_rand($res, $num);
            $count = count($keys);
            for ($i = 0; $i < $count; $i++){
                $ress[] = $res[$keys[$i]];
            }
        }
        // 完整url https://yiluxiaopao.oss-cn-beijing.aliyuncs.com/face/1600410717.493368.jpeg
        $uri = 'https://' . env('OSS_BUCKET') . '.' . env('OSS_ENDPOINT') . '/';
        return array_map(fn($path) => $uri . $path, $ress ?? $res);
    }


    public function getEntrustOrderSharePic($num, $id){
//        $path = 'https://yiluxiaopao.oss-cn-beijing.aliyuncs.com/ylxp-admin/entrust-share.png';
        $path = BASE_PATH . '/storage/entrust-share.png';
        $font = BASE_PATH . '/storage/DINPro-Medium.otf';//字体路径
        $dst = @imagecreatefrompng($path);
        $red = imagecolorallocate($dst, 217, 32, 40);//rgba
        imagefttext($dst, 52, 0, 177, 199, $red, $font, $num);
        $fileName = "/entrust-share-{$id}.jpg";
        $filePath = env('OSS_DIR', 'ylxp-admin').$fileName;
        ob_start();
        imagejpeg($dst);
        $img_data = ob_get_contents();
        ob_end_clean();
        imagedestroy($dst);
        $this->filesystem->write($filePath, $img_data);
        return 'https://'. env('OSS_BUCKET') . '.'  . env('OSS_ENDPOINT') . '/' . $filePath;
    }

    public function generateEntrustOrderSharePic($text, $id){
        $path = BASE_PATH . '/storage/entrust-share.png';
        $font_file = BASE_PATH . '/storage/DINPro-Medium.otf';

        $im = @imagecreatefrompng($path);

        $font_size = 50;
        $font_angle = 0;
        $box   = imagettfbbox($font_size, $font_angle, $font_file, $text);
        $min_x = min( array($box[0], $box[2], $box[4], $box[6]) );
        $max_x = max( array($box[0], $box[2], $box[4], $box[6]) );
        $min_y = min( array($box[1], $box[3], $box[5], $box[7]) );
        $max_y = max( array($box[1], $box[3], $box[5], $box[7]) );
        $width  = ( $max_x - $min_x );
        $height = ( $max_y - $min_y );
        $left   = abs( $min_x );
        $top    = abs( $min_y );

        $stamp     = @imagecreatetruecolor( $width + 35, $height);
        $red = imagecolorallocate($stamp, 217, 32, 40);
        $white = imagecolorallocatealpha($stamp, 255, 255, 255, 0);
        imagecolortransparent($stamp, $white);
        imagefilledrectangle($stamp, 0, 0, imagesx($stamp), imagesy($stamp), $white);

        imagefttext($stamp, $font_size/2, $font_angle, 0, $top, $red, $font_file, '¥');
        imagettftext( $stamp, $font_size, $font_angle, 25, $top, $red, $font_file, $text);

        $sx = imagesx($stamp);
        $sy = imagesy($stamp);

        imagecopymerge($im,$stamp,(int)((imagesx($im) - $sx)/2),(int)((imagesy($im) - $sy * 2)/2),0,0,$sx,$sy,100);

        ob_start();
        imagejpeg($im);
        $img_data = ob_get_contents();
        ob_end_clean();

        imagedestroy($im);

        $fileName = "/entrust-share-{$id}.jpg";
        $filePath = env('OSS_DIR', 'ylxp-admin').$fileName;
        $this->filesystem->write($filePath, $img_data);
        return 'https://'. env('OSS_BUCKET') . '.'  . env('OSS_ENDPOINT') . '/' . $filePath;
    }

}
